package com.hushao.lims.weblims.controller;

import com.hushao.lims.weblims.domain.*;
import com.hushao.lims.weblims.service.*;
import com.hushao.lims.weblims.utils.UserUtil;
import com.hushao.lims.weblims.vo.ResponseData;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 930588706
 * @date 18/1/18
 * 耗材
 */
@Controller
@RequestMapping("/consumable")
public class ConsumableController {

    @Autowired
    private ConsumableService consumableService;
    @Autowired
    private ConsumableRepertoryService consumableRepertoryService;
    @Autowired
    private ConsumableStorageService consumableStorageService;
    @Autowired
    private ConsumableOutgoingService consumableOutgoingService;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private UserUtil userUtil;

    /**
     * 根据耗材名称模糊查询数量大于0的耗材库存（分页）
     * @param consumableName
     * @param async
     * @param pageable
     * @param model
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "查询数量大于0的耗材库存（分页）")
    @PreAuthorize("hasAnyAuthority('ROLE_实验室管理员','ROLE_主管')")
    @GetMapping("/repertorys")
    public String repertorys(@RequestParam(value = "consumableName",required = false,defaultValue = "") String consumableName,
                             @RequestParam(value = "async",required = false) boolean async,
                             Pageable pageable,
                             Model model)throws Exception{
        Page<ConsumableRepertory> repertoryPage=consumableRepertoryService.listConsumableByName(consumableName,pageable);
        List<ConsumableRepertory> consumableRepertories=repertoryPage.getContent();
        model.addAttribute("page",repertoryPage);
        model.addAttribute("consumableRepertories",consumableRepertories);
        TeacherInfo teacher= userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication());

        //获取数据库的角色而不是获取当前静态登陆角色
        TeacherInfo teacher1=teacherService.getById(teacher.getTeacherId());
        boolean isBo=false;
        for (GrantedAuthority r:teacher1.getAuthorities()){
            if("ROLE_实验室管理员".equals(r.getAuthority())){
                isBo=true;
                break;
            }
        }
        model.addAttribute("isBo",isBo);
        return async==true?"/consumables/repertories ::#mainContainerRepleace":"/consumables/repertories";
    }

    /**
     * 获取耗材入库界面
     * @param model
     * @return
     */
    @ApiOperation(value = "获耗材才入库界面")
    @GetMapping("/storage")
    public String storage(Model model){
        model.addAttribute("consumable",new ConsumableInfo(null,null,null,null));
        return "/consumables/add";
    }

    /**
     * 获取耗材出库界面
     * @param consumableId
     * @param model
     * @return
     */
    @ApiOperation("获取耗材出库界面")
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @GetMapping("/outgoing/{consumableId}")
    public String outgoingInterface(@PathVariable("consumableId")Long consumableId, Model model){
        ConsumableInfo consumableInfo=consumableService.findOne(consumableId);
        model.addAttribute("consumable",consumableInfo);
        return "/consumables/outgoing";
    }


    /**
     *耗材入库或出库操作
     * @param consumable
     * @param teacherNumber
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "耗材入库或出库操作服务")
    @PreAuthorize("hasAuthority('ROLE_实验室管理员')")
    @PostMapping("/outgoingOrStorage")
    @ResponseBody
    public ResponseData outgoingOrStorage(ConsumableInfo consumable, Integer consumableCount, @RequestParam(value = "teacherNumber",required = false,defaultValue = "") String teacherNumber)throws Exception{
        String message;
        //获取当前登录者信息
        TeacherInfo teacher= userUtil.isLogged(SecurityContextHolder.getContext().getAuthentication());

        if("".equals(teacherNumber)&&consumable.getConsumableId()==null){
            //入库
            ConsumableStorage consumableStorage=new ConsumableStorage(consumable,consumableCount,teacher,null);
            consumableStorageService.saveConsumableStorage(consumableStorage);
            message="等待审核!";

        }else {
            TeacherInfo receiver= (TeacherInfo) userDetailsService.loadUserByUsername(teacherNumber);
            //出库操作
            ConsumableOutgoing consumableOutgoing=new ConsumableOutgoing(consumable,consumableCount,teacher,receiver,null);
            consumableOutgoingService.outgoing(consumableOutgoing);
            message="出库成功!";
        }
        return new ResponseData(true,message);
    }

}
